#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2025/2/8 10:18
# @Author  : liuyuzhao
# @Site    :
# @File    : tiktok.py
# @Software: PyCharm
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

import os
import time
import json
from datetime import datetime
from utils.trans_date import get_yesterday
from DrissionPage import ChromiumPage
from pipeline.sql_connect import WaicangSqlConnect
from spider.tiktok.click_hanzi import base64_api
from pipeline.redis_connect import save_key_redis, query_redis_cookie
from utils.send_feishu import send_notice
from utils.qiwei_monitor import send_user

def yanzhengma(page, dianxuan):
    """
        过形状点选验证码
    """
    dianxuan.get_screenshot(path='dianxuan.png')
    result = base64_api('./dianxuan.png')
    # print(result)
    hanzi_list = result.split("|")
    for i in range(len(hanzi_list)):
        hanzi = hanzi_list[i]
        left = int(hanzi.split(",")[0])
        right = int(hanzi.split(",")[1])
        print("-----点选第{} 个形状开始".format(i, left, right))
        dianxuan.click.at(offset_x=int(left), offset_y=int(right))
        time.sleep(2)
        print("-----点选第{} 个形状结束".format(i))
    page.ele('xpath://div[@class="TUXButton-label"]').click()
    print('点击确认成功')
    time.sleep(5)
    dianxuan = page.ele('xpath://*[@class="TUXModal captcha-verify-container"]')
    os.remove('dianxuan.png')
    if dianxuan:
        print('验证失败，重试')
        return yanzhengma(page, dianxuan)
    return True

def check_login_success(user, page, wc):
    """
    校验登录是否成功
    :param page:
    :return:
    """
    current_url = page.url
    print(current_url)
    page.refresh()
    time.sleep(3)

    title = page.ele('css:.title')
    if user.get('othername') in page.html:
        print('已经是在登录后的主页面')
        time.sleep(10)
        cookies = page.cookies
        print(cookies)
        update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # save_key_redis(name='tiktok_business_cookie', key=user.get('username'), cookie=json.dumps(cookies, ensure_ascii=False))
        if not wc:
            wc = WaicangSqlConnect()
        wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time, platform_name=user.get('username'))
        return True

    return False


# 创建默认的窗口对象
def login_tiktok_driss(user, count=0):
    """
    登录tiktok_business平台
    """
    page = ChromiumPage()
    wc = WaicangSqlConnect()
    date = get_yesterday(days=0)
    failed_png_path = "./login_tiktok_failed.png"
    if os.path.exists(failed_png_path):
        os.remove(failed_png_path)

    try:
        page.get("https://ads.tiktok.com/i18n/login/")
        if check_login_success(user=user, page=page, wc=wc):
            cookies = page.cookies
            if page.tabs:
                page.close_other_tabs()
                page.close_tabs()
            wc.close()
            return cookies

        old_cookies = wc.query_temu_seller_cookie(platform_name=user.get('username'))
        # old_cookies = query_redis_cookie(name='tiktok_business_cookie', key=user.get('username'))
        if old_cookies:
            ck = json.loads(old_cookies)
            print(ck)
            page.clear_cache(session_storage=False, local_storage=False, cache=False)
            page.set.cookies(ck)
            print("cookie更新")
            page.get("https://ads.tiktok.com/i18n/home")
            time.sleep(1)
            if check_login_success(user=user, page=page, wc=wc):
                print("旧cookie保持登录成功")
                cookies = page.cookies
                if page.tabs:
                    page.close_other_tabs()
                    page.close_tabs()
                wc.close()
                return cookies

        # page.clear_cache(session_storage=False, local_storage=False, cache=False)
        page.get("https://ads.tiktok.com/i18n/login/")
        time.sleep(3)

        # 选择语言为中文
        # page.ele('xpath://*[@class="ac-lang-avater__lang-btn"]').click()
        # time.sleep(2)
        # page.ele('xpath://*[@class="ac-lang-avater__lang-modal__container__item"][2]').click
        # time.sleep(5)

        page.ele('xpath://input[@type="email"]').input(user.get('username'))
        print('输入账号成功')

        page.ele('xpath://input[@type="password"]').input(user.get('password'))
        print('输入密码成功')
        time.sleep(3)

        page.ele('xpath://button[@id="TikTok_Ads_SSO_Login_Btn_new"]').click()
        print('点击登录成功')
        time.sleep(3)


        dianxuan = page.ele('xpath://*[@class="TUXModal captcha-verify-container"]')
        if dianxuan:
            print('出现形状点选验证码，开始处理')
            yanzhengma(page, dianxuan)
        time.sleep(60)

        youxiang = page.ele('xpath://div[@class="ac-sendcode-separate-input__text"]/h3')
        if youxiang and (youxiang.text == '2-step verification' or youxiang.text == '双重验证'):
            print('出现邮箱验证，请联系人工处理')
            # send_notice(content=f'{date} 【海外电商】tiktok广告平台登录出现邮箱验证码，账号：{user.get("username")}，请开发人员排查')
            send_user(content=f'{date} 【海外电商】tiktok广告平台登录出现邮箱验证码，账号：{user.get("username")}，请开发人员排查')
            # time.sleep(100)

        title = page.ele('xpath://*[@class="title"]')
        othername = page.ele('xpath://div[@class="text-ellipsis"]/span').text.replace(' ', '')
        result = check_login_success(user=user, page=page, wc=wc)
        if result:
            print('登录成功，cookies值已更新')
        else:
            print(f'账号：{user.get("username")}，执行登录异常，请开发人员排查')
            # send_notice(content=f'{date} 【海外电商】tiktok广告平台登录失败，账号：{user.get("username")}，请开发人员排查')
            send_user(content=f'{date} 【海外电商】tiktok广告平台登录失败，账号：{user.get("username")}，请开发人员排查')
            return {}

    except Exception as e:
        page.get_screenshot(failed_png_path)
        print(e)
        if count == 0:
            count += 1
            print(f"账号：{user.get('username')}，执行登录异常，重试中")
            return login_tiktok_driss(user=user, count=count)
        print(f"账号：{user.get('username')}，执行登录异常，请开发人员排查")
        # send_notice(content=f'{date} 【海外电商】tiktok广告平台登录失败，账号：{user.get("username")}，请开发人员排查')
        send_user(content=f'{date} 【海外电商】tiktok广告平台登录失败，账号：{user.get("username")}，请开发人员排查')
        if page.tabs:
            page.close_other_tabs()
            page.close_tabs()
        return {}


if __name__ == '__main__':
    # 跨境平台爬虫需求沟通，邮箱验证码找郭占豪同事
    userlist=[
        # {'username':'MinisoUS@miniso.com', 'password':'MiNiSo!123', 'othername':'MinisoUS-overseas'},
        {'username':'TiktokUS01@miniso.com', 'password':'#ujumedia2025', 'othername':'名创优品跨境电商（广州）有限公司'},
        # {'username':'TiktokUS02@miniso.com', 'password':'TKminiso036/', 'othername':'MINISO OFFICIAL'},
        # {'username': 'TiktokUScccu01@miniso.com', 'password': 'Miniso!2025', 'othername': 'TOY FUNVIBE'},
    ]
    for user in userlist:
        login_tiktok_driss(user)